<?php
namespace Backend\Models\ServerPlatform\Task;

use Backend\Models\Base;

class Type extends Base
{
    public function initialize()
    {
        parent::initialize();
    }

    public function getSource()
    {
        return 'daishu_task_type';
    }

    /**
     *
     * @param $limit
     * @param $offset
     *
     * @return bool
     */
    public function gets($limit, $offset)
    {
        $query = $this->queryBuilder()->columns('*')->from(self::class);
        try {
            $ret = $query->orderBy('id DESC')->limit($limit, $offset)->getQuery()->execute();
            if ($ret !== false) {
                return $ret->toArray();
            }
        } catch (\PDOException $ex) {
            $this->errorLog('SELECT', $query->getPhql(), $ex->getMessage(), __FILE__, __LINE__);
        }
        return false;
    }

    /**
     *
     * @return bool
     */
    public function getCount()
    {
        $query = $this->queryBuilder()->columns('COUNT(0) AS cnt')->from(self::class);
        try {
            $ret = $query->getQuery()->execute()->toArray();
            if ($ret !== false) {
                return $ret[0]['cnt'];
            }
        } catch (\PDOException $ex) {
            $this->errorLog('SELECT', $query->getPhql(), $ex->getMessage(), __FILE__, __LINE__);
        }
        return false;
    }

    public function add($entity)
    {
        try {
            if ($this->db()->insertAsDict(self::getSource(), $entity)) {
                return true;
            }
        } catch (\PDOException $ex) {
            $this->errorLog('INSERT', $this->db()->getSQLStatement(), $ex->getMessage(), __FILE__, __LINE__);
        }
        return false;
    }

    public function get($id)
    {
        $id = intval($id);
        try {
            $query = 'SELECT * FROM `daishu_task_type` WHERE `id`=' . $id;
            $ret   = $this->db()->query($query)->fetch();
            if ($ret !== false && is_array($ret) && count($ret) > 0) {
                return $ret;
            }
        } catch (\PDOException $ex) {
            $this->errorLog('SELECT', $this->db()->getSQLStatement(), $ex->getMessage(), __FILE__, __LINE__);
        }
        return false;
    }

    public function edit($entity)
    {
        try {
            if ($this->db()->updateAsDict(self::getSource(), $entity, sprintf('id=%d LIMIT 1', intval($entity['id'])))) {
                return true;
            }
        } catch (\PDOException $ex) {
            $this->errorLog('UPDATE', $this->db()->getSQLStatement(), $ex->getMessage(), __FILE__, __LINE__);
        }
        return false;
    }

}
